using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PointOfSale.Global;
using System.Data .SqlClient;
using System.Data;
using System.Text.RegularExpressions;
using PointOfSale.Class;


namespace PointOfSale.Configuration.Item
{
	public class frmItemDepartment : System.Windows.Forms.Form
	{
		private System.Windows.Forms.TextBox txtMinQty;
		private System.Windows.Forms.TextBox txtMaxQty;
		private System.Windows.Forms.TextBox txtOpt;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.ListView listView1;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.Button btnAdd;
		private System.Windows.Forms.Button btnUpdate;
		private System.Windows.Forms.Button btnDelete;
		private System.Windows.Forms.ColumnHeader clhName;
		private System.Windows.Forms.ColumnHeader clhMinQty;
		private System.Windows.Forms.ColumnHeader clhMaxQty;
		private System.Windows.Forms.ColumnHeader clhOpt;
		private System.Windows.Forms.ColumnHeader clhNowHave;

		private System.ComponentModel.Container components = null;

		private SqlDataAdapter dataAdapter;
		private SqlCommand sqlCommand;
		private DataSet dataSet;
		private System.Windows.Forms.ColumnHeader clhItemID;

		private ListView.CheckedListViewItemCollection checkedRow = null;
		private System.Windows.Forms.Button btnSave;
		private ListView.SelectedListViewItemCollection row = null;
		private System.Windows.Forms.LookupComboBox cboItem;
		private string selectedItemID = "";


		public frmItemDepartment()
		{

			InitializeComponent();
		}

		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.txtMinQty = new System.Windows.Forms.TextBox();
			this.txtMaxQty = new System.Windows.Forms.TextBox();
			this.txtOpt = new System.Windows.Forms.TextBox();
			this.label1 = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.listView1 = new System.Windows.Forms.ListView();
			this.clhName = new System.Windows.Forms.ColumnHeader();
			this.clhMinQty = new System.Windows.Forms.ColumnHeader();
			this.clhMaxQty = new System.Windows.Forms.ColumnHeader();
			this.clhOpt = new System.Windows.Forms.ColumnHeader();
			this.clhNowHave = new System.Windows.Forms.ColumnHeader();
			this.clhItemID = new System.Windows.Forms.ColumnHeader();
			this.label4 = new System.Windows.Forms.Label();
			this.btnAdd = new System.Windows.Forms.Button();
			this.btnUpdate = new System.Windows.Forms.Button();
			this.btnDelete = new System.Windows.Forms.Button();
			this.btnSave = new System.Windows.Forms.Button();
			this.cboItem = new System.Windows.Forms.LookupComboBox();
			this.SuspendLayout();
			// 
			// txtMinQty
			// 
			this.txtMinQty.Location = new System.Drawing.Point(8, 80);
			this.txtMinQty.Name = "txtMinQty";
			this.txtMinQty.Size = new System.Drawing.Size(96, 20);
			this.txtMinQty.TabIndex = 0;
			this.txtMinQty.Text = "";
			// 
			// txtMaxQty
			// 
			this.txtMaxQty.Location = new System.Drawing.Point(120, 80);
			this.txtMaxQty.Name = "txtMaxQty";
			this.txtMaxQty.Size = new System.Drawing.Size(88, 20);
			this.txtMaxQty.TabIndex = 1;
			this.txtMaxQty.Text = "";
			// 
			// txtOpt
			// 
			this.txtOpt.Location = new System.Drawing.Point(216, 80);
			this.txtOpt.Name = "txtOpt";
			this.txtOpt.Size = new System.Drawing.Size(96, 20);
			this.txtOpt.TabIndex = 2;
			this.txtOpt.Text = "";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(8, 64);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(96, 16);
			this.label1.TabIndex = 3;
			this.label1.Text = "Min Qty";
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(120, 64);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(88, 16);
			this.label2.TabIndex = 4;
			this.label2.Text = "Max Qty";
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(216, 64);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(88, 16);
			this.label3.TabIndex = 5;
			this.label3.Text = "Opt Qty";
			// 
			// listView1
			// 
			this.listView1.CheckBoxes = true;
			this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
																						this.clhName,
																						this.clhMinQty,
																						this.clhMaxQty,
																						this.clhOpt,
																						this.clhNowHave,
																						this.clhItemID});
			this.listView1.FullRowSelect = true;
			this.listView1.GridLines = true;
			this.listView1.HideSelection = false;
			this.listView1.Location = new System.Drawing.Point(8, 104);
			this.listView1.Name = "listView1";
			this.listView1.Size = new System.Drawing.Size(816, 416);
			this.listView1.TabIndex = 6;
			this.listView1.View = System.Windows.Forms.View.Details;
			this.listView1.Click += new System.EventHandler(this.listView1_Click);
			this.listView1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.listView1_MouseUp);
			// 
			// clhName
			// 
			this.clhName.Text = "Name";
			this.clhName.Width = 300;
			// 
			// clhMinQty
			// 
			this.clhMinQty.Text = "Min Qty";
			this.clhMinQty.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
			this.clhMinQty.Width = 100;
			// 
			// clhMaxQty
			// 
			this.clhMaxQty.Text = "Max Qty";
			this.clhMaxQty.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
			this.clhMaxQty.Width = 100;
			// 
			// clhOpt
			// 
			this.clhOpt.Text = "Opt Qty";
			this.clhOpt.Width = 100;
			// 
			// clhNowHave
			// 
			this.clhNowHave.Text = "Now Have";
			this.clhNowHave.Width = 212;
			// 
			// clhItemID
			// 
			this.clhItemID.Width = 0;
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(8, 8);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(88, 16);
			this.label4.TabIndex = 8;
			this.label4.Text = "Item";
			// 
			// btnAdd
			// 
			this.btnAdd.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.btnAdd.Location = new System.Drawing.Point(320, 72);
			this.btnAdd.Name = "btnAdd";
			this.btnAdd.Size = new System.Drawing.Size(64, 24);
			this.btnAdd.TabIndex = 9;
			this.btnAdd.Text = "Add";
			this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
			// 
			// btnUpdate
			// 
			this.btnUpdate.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.btnUpdate.Location = new System.Drawing.Point(672, 528);
			this.btnUpdate.Name = "btnUpdate";
			this.btnUpdate.Size = new System.Drawing.Size(72, 24);
			this.btnUpdate.TabIndex = 10;
			this.btnUpdate.Text = "Update";
			this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
			// 
			// btnDelete
			// 
			this.btnDelete.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.btnDelete.Location = new System.Drawing.Point(752, 528);
			this.btnDelete.Name = "btnDelete";
			this.btnDelete.Size = new System.Drawing.Size(72, 24);
			this.btnDelete.TabIndex = 11;
			this.btnDelete.Text = "Delete";
			this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
			// 
			// btnSave
			// 
			this.btnSave.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.btnSave.Location = new System.Drawing.Point(584, 528);
			this.btnSave.Name = "btnSave";
			this.btnSave.Size = new System.Drawing.Size(80, 24);
			this.btnSave.TabIndex = 12;
			this.btnSave.Text = "Save";
			this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
			// 
			// cboItem
			// 
			this.cboItem.Location = new System.Drawing.Point(8, 32);
			this.cboItem.Name = "cboItem";
			this.cboItem.Size = new System.Drawing.Size(176, 21);
			this.cboItem.TabIndex = 13;
			// 
			// frmItemDepartment
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(832, 557);
			this.Controls.Add(this.cboItem);
			this.Controls.Add(this.btnSave);
			this.Controls.Add(this.btnDelete);
			this.Controls.Add(this.btnUpdate);
			this.Controls.Add(this.btnAdd);
			this.Controls.Add(this.label4);
			this.Controls.Add(this.listView1);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.txtOpt);
			this.Controls.Add(this.txtMaxQty);
			this.Controls.Add(this.txtMinQty);
			this.Name = "frmItemDepartment";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Item - Department";
			this.Load += new System.EventHandler(this.frmItemDepartment_Load);
			this.ResumeLayout(false);

			this.label1.Text = clsGlobal.g_Hashtable["ItemDepartmentMinQty"].ToString();
			this.label2.Text = clsGlobal.g_Hashtable["ItemDepartmentMaxQty"].ToString();
			this.label3.Text = clsGlobal.g_Hashtable["ItemDepartmentOptQty"].ToString();
			this.clhName.Text = clsGlobal.g_Hashtable["ItemDepartmentlsvName"].ToString();
			this.clhMinQty.Text = clsGlobal.g_Hashtable["ItemDepartmentlsvMinQty"].ToString();
			this.clhMaxQty.Text = clsGlobal.g_Hashtable["ItemDepartmentlsvMaxQty"].ToString();
			this.clhOpt.Text = clsGlobal.g_Hashtable["ItemDepartmentlsvOptQty"].ToString();
			this.clhNowHave.Text = clsGlobal.g_Hashtable["ItemDepartmentlsvNowHave"].ToString();
			this.label4.Text = clsGlobal.g_Hashtable["ItemDepartmentItemName"].ToString();
			this.btnAdd.Text = clsGlobal.g_Hashtable["ItemDepartmentbtnAdd"].ToString();
			this.btnUpdate.Text = clsGlobal.g_Hashtable["ItemDepartmentbtnUpdate"].ToString();
			this.btnDelete.Text = clsGlobal.g_Hashtable["ItemDepartmentbtnDelete"].ToString();
			this.btnSave.Text = clsGlobal.g_Hashtable["ItemDepartmentbtnSave"].ToString();
			this.Text = clsGlobal.g_Hashtable["ItemDepartmentFormName"].ToString();
		}
		#endregion

		public void LoadDataToListView()
		{
			string SelectCommand = "select a.ItemName, a.ItemId, c.MinQty, c.MaxQty, c.OptQty from tblItem a, tblItemDepartment c where a.itemID = c.ItemID and c.DepartmentID = " + clsGlobal.g_DepartmentId + "ORDER BY a.ItemName";
			DataTable dr = clsDatabase.GetDataToTable(SelectCommand, clsGlobal.g_DataConn);
			
			string strName, strMinQty, strMaxQty, strNowHave, strOptQty, strItemID;
			listView1.Items.Clear();
			int nItem = dr.Rows.Count;

			for(int i = 0; i < nItem; i ++)
			{
				strName= dr.Rows[i][0].ToString();
				strMinQty= dr.Rows[i][2].ToString();
				if(strMinQty == "0.0")
				{
					strMinQty = "";
				}
				strMaxQty= dr.Rows[i][3].ToString();
				if(strMaxQty == "0.0")
				{
					strMaxQty = "";
				}
				strNowHave= "0.0";
				if(strNowHave == "0.0")
				{
					strNowHave = "";
				}
				strOptQty= dr.Rows[i][4].ToString();
				if(strOptQty == "0.0")
				{
					strOptQty = "";
				}
				strItemID = dr.Rows[i][1].ToString();

				//Lay thong tin ve luong hang ton trong kho.
				String strSelect = "SELECT ItemId, tblStock.UnitId, UnitName, QtyInHand FROM tblStock, tblUnit WHERE tblStock.UnitId = tblUnit.UnitId AND ItemId = " + strItemID;
				DataTable dt = clsDatabase.GetDataToTable(strSelect, clsGlobal.g_DataConn);
				int n = dt.Rows.Count;
				String strQty = "";
				for(int j = 0; j < n; j ++)
				{
					strQty = strQty + dt.Rows[j][3].ToString() + " " + dt.Rows[j][2].ToString() + " ";
				}

				ListViewItem TempListViewItem = new ListViewItem (new string[]{ strName, strMinQty, strMaxQty, strOptQty, strQty, strItemID});
				listView1.Items .Add (TempListViewItem);
			}
		}

		private void frmItemDepartment_Load(object sender, System.EventArgs e)
		{
			//Dua du lieu tu bang tblItemDepartment vao ListView
			LoadDataToListView();
			
			DataTable dt = clsItem.GetNotYetItem(clsGlobal.g_DepartmentId);
			cboItem.DataSource = dt;
			cboItem.DisplayMember = "ItemName";
			cboItem.ValueMember = "ItemId";

			this.sqlCommand = new SqlCommand();
			this.sqlCommand.Connection = clsGlobal.g_DataConn;


			this.dataAdapter = new SqlDataAdapter();
			this.dataAdapter.SelectCommand = this.sqlCommand;

			this.dataSet = new System.Data.DataSet();
			this.dataSet.CaseSensitive = true;

			//Xu ly hien thi ban dau tren form
			this.btnDelete.Enabled = false;
			this.btnUpdate.Enabled = false;
		}

		//
		//Ham load danh sach cac item len combo box
		//
		private void loadItemList()
		{
			DataTable dt = clsItem.GetNotYetItem(clsGlobal.g_DepartmentId);
			cboItem.DisplayMember = "ItemName";
			cboItem.ValueMember = "ItemId";
			if(this.cboItem.Items.Count != 0)
			{
				this.cboItem.SelectedItem = this.cboItem.Items[0];
			}
		}

		//Ham kiem tra du lieu tren form
		private string checkFormForAdd()
		{
			string result = "";
			//Kiem tra item nay da co trong department nay chua
			string itemID = "";
			string selectCommand = "select itemID from tblItem where itemName = N'" + this.cboItem.Text + "'";
			SqlCommand _sqlCommand = new SqlCommand(selectCommand,clsGlobal.g_DataConn);
			SqlDataReader dr = _sqlCommand.ExecuteReader();
			while(dr.Read())
			{
				itemID = dr["itemID"].ToString();
			}
			dr.Close();

			selectCommand = "select itemid from tblitemdepartment where departmentid = "  + clsGlobal.g_DepartmentId + " and itemID = " + itemID;//////////////////////////////////////////////////
			_sqlCommand = new SqlCommand(selectCommand,clsGlobal.g_DataConn);
			dr = _sqlCommand.ExecuteReader();
			if(dr.HasRows)
			{
				result += clsGlobal.g_Hashtable["msgItemDepartmentItemExisted"].ToString();
			}	
			dr.Close();

			result += checkFormForUpdate();

			return result;
		}

		private string checkFormForUpdate()
		{
			string result = "";
			//Kiem tra minqty, maxqty, optqty la so float
			string minQty = this.txtMinQty.Text;
			Match match = Regex.Match(minQty, "[0-9]+[.]*[0-9]*");
			if(match.ToString() != minQty)
			{
				result += clsGlobal.g_Hashtable["msgItemDepartmentMinIsNumber"].ToString();
			}
			
			string maxQty = this.txtMaxQty.Text;
			match = Regex.Match(maxQty, "[0-9]+[.]*[0-9]*");
			if(match.ToString() != maxQty)
			{
				result += clsGlobal.g_Hashtable["msgItemDepartmentMaxIsNumber"].ToString();
			}
			
			string optQty = this.txtOpt.Text;
			match = Regex.Match(optQty, "[0-9]+[.]*[0-9]*");
			if(match.ToString() != optQty)
			{
				result += clsGlobal.g_Hashtable["msgItemDepartmentOptIsNumber"].ToString();
			}
			return result;
		}

		private void btnAdd_Click(object sender, System.EventArgs e)
		{
			//Neu du lieu tren form la hop le
			string checkResult = checkFormForAdd();
			if(checkResult.Length == 0)
			{
				//Xac dinh item id
				int itemID = Convert.ToInt32(cboItem.SelectedValue.ToString());
				
				clsItemDepartment itemDept = new clsItemDepartment();

				itemDept.ItemId = itemID;

				if(this.txtMinQty.Text.Length != 0)
				{
					itemDept.MinQty = Convert.ToDouble(this.txtMinQty.Text);
				}
				if(this.txtMaxQty.Text.Length != 0)
				{
					itemDept.MaxQty = Convert.ToDouble(this.txtMaxQty.Text);
				}
				if(this.txtOpt.Text.Length != 0)
				{
					itemDept.OptQty = Convert.ToDouble(this.txtOpt.Text);
				}

				itemDept.Add();

				//Them vao bang Stock voi luong hang bang 0 trong kho.
				//Lay toan bo thong tin item va unit
				String strSelect = "SELECT UnitSourceId, UnitDestId FROM tblUnitConversion WHERE ItemId = " + itemID;
				DataTable dt = clsDatabase.GetDataToTable(strSelect, clsGlobal.g_DataConn);
				int n = dt.Rows.Count;
				for (int i = 0; i < n; i ++)
				{
					//Kiem tra xem trong bang stock da co chua
					strSelect = "SELECT * FROM tblStock WHERE ItemId = " + itemID + 
										" AND UnitId = " + dt.Rows[i][0].ToString();
					DataTable testTable = clsDatabase.GetDataToTable(strSelect, clsGlobal.g_DataConn);
					if (testTable.Rows.Count == 0)
					{
						String strInsert = "INSERT tblStock(ItemId, DepartmentId, UnitId, QtyInHand) VALUES(" +
										itemID + ", " +
										clsGlobal.g_DepartmentId + ", " +
										dt.Rows[i][0].ToString()+ ", " +
										"0)";
						clsDatabase.ExecuteSQL(strInsert, clsGlobal.g_DataConn);
					}

					//Kiem tra xem trong bang stock da co chua
					strSelect = "SELECT * FROM tblStock WHERE ItemId = " + itemID + 
						"AND UnitId = " + dt.Rows[i][1].ToString();
					testTable = clsDatabase.GetDataToTable(strSelect, clsGlobal.g_DataConn);
					if (testTable.Rows.Count == 0)
					{
						String strInsert = "INSERT tblStock(ItemId, DepartmentId, UnitId, QtyInHand) VALUES(" +
							itemID + ", " +
							clsGlobal.g_DepartmentId + ", " +
							dt.Rows[i][1].ToString()+ ", " +
							"0)";
						clsDatabase.ExecuteSQL(strInsert, clsGlobal.g_DataConn);
					}
				}

				//Load lai data len listview
				this.LoadDataToListView();
				loadItemList();

				dt = clsItem.GetNotYetItem(clsGlobal.g_DepartmentId);
				cboItem.DataSource = dt;
				cboItem.DisplayMember = "ItemName";
				cboItem.ValueMember = "ItemId";
			}
			else
			{
				MessageBox.Show(checkResult);
			}
		}

		private void btnDelete_Click(object sender, System.EventArgs e)
		{
			this.checkedRow = this.listView1.CheckedItems;
			string itemID = "";
			foreach(ListViewItem item in this.checkedRow)
			{
				itemID = item.SubItems[5].Text;
				this.sqlCommand.CommandText = "delete tblItemDepartment where itemID = " + itemID + " and departmentID = "  + clsGlobal.g_DepartmentId;//////////////////////
				this.dataAdapter.Fill(this.dataSet);
				this.dataSet.Clear();

				this.LoadDataToListView();
				this.btnDelete.Enabled = false;
			}
		}

		private void listView1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			this.row = listView1.SelectedItems;
			this.checkedRow = listView1.CheckedItems;
			if(this.checkedRow.Count == 0)
			{
				this.btnDelete.Enabled = false;

				if(this.row.Count == 0)
				{
					this.AcceptButton = this.btnSave;
				}
			}
			else
			{
				this.btnDelete.Enabled = true;
			}

			if(this.row.Count == 0)
			{
				this.btnUpdate.Enabled = false;

				if(this.checkedRow.Count == 0)
				{
					this.AcceptButton = this.btnSave;
				}
			}
			else
			{
				this.btnUpdate.Enabled = true;
			}
		}

		private void listView1_Click(object sender, System.EventArgs e)
		{
			this.row = this.listView1.SelectedItems;
			if(this.row.Count != 0)
			{
				this.selectedItemID = this.listView1.FocusedItem.SubItems[5].Text;

				this.txtMinQty.Text = this.listView1.FocusedItem.SubItems[1].Text;
				this.txtMaxQty.Text = this.listView1.FocusedItem.SubItems[2].Text;
				this.txtOpt.Text = this.listView1.FocusedItem.SubItems[3].Text;
			}
		}

		private void btnUpdate_Click(object sender, System.EventArgs e)
		{
			string checkResult = checkFormForUpdate();
			if(checkResult.Length == 0)
			{
				this.sqlCommand.CommandText = "update tblItemDepartment set ";
				if(this.txtMinQty.Text.Length != 0)
				{
					this.sqlCommand.CommandText += "MinQty = " + this.txtMinQty.Text;
				}
				else
				{
					this.sqlCommand.CommandText += "MinQty = null";
				}

				if(this.txtMaxQty.Text.Length != 0)
				{
					this.sqlCommand.CommandText += ", MaxQty = " + this.txtMaxQty.Text;
				}
				else
				{
					this.sqlCommand.CommandText += ", MaxQty = null";
				}
				if(this.txtOpt.Text.Length != 0)
				{
					this.sqlCommand.CommandText += ", OptQty = " + this.txtOpt.Text;
				}
				else
				{
					this.sqlCommand.CommandText += ", OptQty = null";
				}
				this.sqlCommand.CommandText += " where itemID = " + this.selectedItemID + " and departmentID = " + clsGlobal.g_DepartmentId;///////////////////
				this.dataAdapter.Fill(this.dataSet);
				this.dataSet.Clear();
				
				this.LoadDataToListView();
			}
			else
			{
				MessageBox.Show(checkResult);
			}
		}

		private void btnSave_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}
	}
}
